package cn.lisens.async.web;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.annotation.PostConstruct;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
public class DeferredResultController {

	// 模拟任务队列
    private final Queue<DeferredResult<String>> taskQueue = new ConcurrentLinkedQueue<>();
    
    @GetMapping("/async/deferred")
    public DeferredResult<String> asyncDeferred() {
        DeferredResult<String> deferredResult = new DeferredResult<>(5000L, "超时默认响应");
        
        deferredResult.onTimeout(() -> {
            System.out.println("请求超时");
            deferredResult.setErrorResult("请求处理超时");
        });
        
        deferredResult.onCompletion(() -> {
            System.out.println("请求完成");
        });
        
        // 将任务加入队列
        taskQueue.add(deferredResult);
        
        return deferredResult;
    }
    
    // 模拟处理任务的线程
    @PostConstruct
    public void processTasks() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                    DeferredResult<String> result = taskQueue.poll();
                    if (result != null) {
                        String response = "处理结果 - " + System.currentTimeMillis();
                        result.setResult(response);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
        thread.start();
    }
}
